import React, { Fragment, useState, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { getChannelUserList, getCountChannelList } from '@/services/channel'
import {
  Card,
  Row,
  Col,
  Button,
  Table,
  Pagination,
  Select,
  Input,
  message,
  Tag,
  Icon,
  DatePicker
} from 'antd'

import moment from 'moment'
import channelStyles from './index.less'
const { RangePicker } = DatePicker
const { Option } = Select

const ChannelUser = () => {
  const columns = [
    {
      title: '注册时间',
      dataIndex: 'createTime',
      align: 'center'
    },
    {
      title: '用户姓名',
      dataIndex: 'userName',
      align: 'center'
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      align: 'center'
    },
    {
      title: '身份证号',
      dataIndex: 'idCardNo',
      align: 'center'
    },
    {
      title: '是否认证',
      dataIndex: 'isAuth',
      align: 'center',
      render: isAuth => (
        <Icon
          style={{ fontSize: 19 }}
          type={isAuth ? 'check-circle' : 'close-circle'}
          theme="twoTone"
          twoToneColor={isAuth ? '#48bc19' : '#f9a314'}
        />
      )
    },
    {
      title: '订单状态',
      dataIndex: 'name3',
      align: 'center',
      render: (text, record) => {
        // record.userOrdersDtoList
        // status 如果包括 '04' '05' '06' 审核通过 '11' 待审批
        // closeType -> 审核拒绝
        // const passStatus = ['04', '05', '06']
        const statusMap = {
          '11': '待审核',
          '09': '审核成功',
          '10': '审核失败'
        }
        switch (record.status) {
          case '09':
            return <Tag color="blue">{statusMap[record.status]}</Tag>
          case '10':
            return <Tag color="#f50">{statusMap[record.status]}</Tag>
          case '11':
            return <Tag color="orange">{statusMap[record.status]}</Tag>
          default:
            break
        }
        return statusMap[record.status]
      }
    }
  ]

  const [userList, setUserList] = useState([])
  const [total, setTotal] = useState(0)
  const [telephone, setTelephone] = useState('')
  const [selectedValue, setSelectedValue] = useState('')
  const [orderTime, setOrderTime] = useState(null)
  const [registerTime, setRegisterTime] = useState(null)

  const [pageInfo, setPageInfo] = useState({
    channelCode: '',
    telephone: '',
    pageNumber: 1,
    pageSize: 10,
    registerStartTime: '',
    registerEndTime: '',
    orderStatus: '',
    orderStartTime: '',
    orderEndTime: ''
  })

  const onHandleRegisterTimeChange = (date, dateString) => {
    const [registerStartTime, registerEndTime] = dateString
    if (!registerStartTime) {
      setPageInfo({
        ...pageInfo,
        registerStartTime,
        registerEndTime
      })
      setRegisterTime(null)
    } else {
      setPageInfo({
        ...pageInfo,
        registerStartTime,
        registerEndTime
      })
      setRegisterTime([moment(registerStartTime), moment(registerEndTime)])
    }
  }

  const onHandlerOrderTimeChange = (date, dateString) => {
    const [orderStartTime, orderEndTime] = dateString
    if (!orderStartTime) {
      setPageInfo({
        ...pageInfo,
        orderStartTime,
        orderEndTime
      })
      setOrderTime(null)
    } else {
      setPageInfo({
        ...pageInfo,
        orderStartTime,
        orderEndTime
      })
      setOrderTime([moment(orderStartTime), moment(orderEndTime)])
    }
  }

  const onReset = () => {
    setPageInfo({
      ...pageInfo,
      pageNumber: 1,
      pageSize: 10,
      channelCode: '',
      registerStartTime: '',
      registerEndTime: '',
      orderStatus: '',
      orderStartTime: '',
      orderEndTime: ''
    })
    setSelectedValue('')
    setOrderTime([])
    setRegisterTime([])
    setTelephone('')
  }

  const onSearchBtn = () => {
    setUserList([])
    setPageInfo({ ...pageInfo, pageNumber: 1, pageSize: 10, telephone })
  }

  const loadList = async () => {
    setUserList([])
    try {
      const params = { ...pageInfo }
      const { data } = await getChannelUserList(params)
      setUserList(data.records)
      setTotal(data.total)
    } catch (error) {
      message.error(error.message)
    }
  }

  const [channelList, setChannelList] = useState([])

  const loadChannelList = async () => {
    try {
      const { data } = await getCountChannelList()
      setChannelList(data)
    } catch (error) {
      message.error(error.message)
    }
  }

  useEffect(() => {
    loadChannelList()
  }, [])

  useEffect(() => {
    loadList()
  }, [pageInfo])

  const onPageChange = pageNumber => {
    setPageInfo({ ...pageInfo, pageNumber })
  }

  const onSizeChange = (current, pageSize) => {
    setPageInfo({ ...pageInfo, pageSize })
  }

  const handleChange = channelCode => {
    setPageInfo({
      ...pageInfo,
      pageNumber: 1,
      channelCode
    })
    setSelectedValue(channelCode)
  }

  const handleOrderStatusChange = orderStatus => {
    setPageInfo({ ...pageInfo, pageNumber: 1, orderStatus })
  }

  return (
    <Fragment>
      <PageHeaderWrapper title="渠道管理">
        <Card>
          <Row gutter={16}>
            <Col span={24}>
              <Row type="flex" justify="space-between">
                <Row type="flex" gutter={20}>
                  <Col>
                    手机号：
                    <Input
                      placeholder="请输入手机号"
                      style={{ width: 150 }}
                      value={telephone}
                      onChange={e => setTelephone(e.target.value)}
                    />
                  </Col>
                  <Col>
                    渠道：
                    <Select
                      showSearch
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.props.children
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      }
                      defaultValue={selectedValue}
                      value={selectedValue}
                      style={{ width: 120 }}
                      onChange={handleChange}
                    >
                      {/* {channelList.length !== 1 && (
                        <Option value="">全部</Option>
                      )} */}
                      <Option value="">全部</Option>
                      {channelList.map(item => (
                        <Option value={item.channelCode} key={item.channelCode}>
                          {item.channelName}
                        </Option>
                      ))}
                    </Select>
                  </Col>
                  <Col>
                    审核状态：
                    <Select
                      style={{ width: 120 }}
                      placeholder="请选择"
                      onChange={handleOrderStatusChange}
                      value={pageInfo.orderStatus}
                    >
                      <Option value="">全部</Option>
                      <Option value="11">待审批</Option>
                      <Option value="09">审批通过</Option>
                      <Option value="10">审批失败</Option>
                    </Select>
                  </Col>
                  <Col>
                    下单时间：
                    <RangePicker
                      style={{ width: 230 }}
                      onChange={onHandlerOrderTimeChange}
                      value={orderTime}
                    />
                  </Col>
                  <Col>
                    <span>注册时间：</span>
                    <RangePicker
                      style={{ width: 230 }}
                      onChange={onHandleRegisterTimeChange}
                      value={registerTime}
                    />
                  </Col>
                </Row>
                <Row style={{ marginTop: 10, width: '100%' }} type="flex">
                  {/* <Col>
                    <span>注册时间：</span>
                    <RangePicker
                      style={{ width: 240 }}
                      onChange={onHandleRegisterTimeChange}
                      value={registerTime}
                    />
                  </Col> */}
                  <Button type="primary" onClick={onSearchBtn}>
                    查询
                  </Button>
                  <Button type="info" onClick={onReset}>
                    重置
                  </Button>
                </Row>
              </Row>
            </Col>
          </Row>

          <Table
            className={channelStyles.table}
            bordered
            dataSource={userList}
            columns={columns}
            pagination={false}
            rowKey="uid"
          />

          <Pagination
            style={{ marginTop: 20, textAlign: 'right' }}
            showTotal={t => `共有 ${t} 条`}
            total={total}
            current={pageInfo.pageNumber}
            pageSize={pageInfo.pageSize}
            defaultPageSize={5}
            pageSizeOptions={['10', '20', '30', '50']}
            showSizeChanger
            showQuickJumper
            onChange={onPageChange}
            onShowSizeChange={onSizeChange}
          />
        </Card>
      </PageHeaderWrapper>
    </Fragment>
  )
}

export default ChannelUser
